import React from "react";
import {Alert, Collapse, Icon, Table, Tag, Spin, Modal, Button, Tooltip, Popover} from 'antd';
import {GiftDeclareTitle} from "containers/request/gift-declare/gift-declare";
import {messages} from "share/common";
import GreenCodeService from './green-code-service'
import errorMessage from "share/errorMessage";
import CheckOptionsMap from './check-options.json'
import CheckOptionsColumnMap from './check-option-column.json'
import columnsWidthMap from './columnsWidth.json'
import ColumnMap from './columns.json'
import './style.scss'
import ReactIF from "components/UI/ReactIF";

const {Panel} = Collapse;

function callback(key) {
  console.log(key);
}

class GreenCodeStateCollapse extends React.Component {
  constructor(props) {
    super(props);

    const {readonly, user, hrInfo, showVisible, hideVisible} = this.props

    // 申请人OID
    const userOID = readonly ? '' : (hrInfo ? hrInfo.userOID : user.userOID)

    this.state = {
      loading: false, userOID: userOID, checkResult: {list: []}, optionList: [], timeoutVisible: false, timeoutTask: -1
    }
  }

  checkAll = () => {

    const {readonly, user, hrInfo, showVisible, hideVisible} = this.props
    hideVisible && hideVisible()
    this.setState({
      loading: true
    })
    GreenCodeService.checkAll(this.state.userOID, 0, 10).then(res => {
      this.setState({
        checkResult: res.data,
        loading: false,
        checkDate: new Date().getTime(),
        // 禁用超时功能
        // timeoutTask: setTimeout(() => this.setState({timeoutVisible: true}), 60 * 1000)
      })
      this.setState({timeoutVisible: false})
      if (res.data.success) {
        showVisible && showVisible()
      } else {
        hideVisible && hideVisible()
      }
    }).catch((err) => {
      errorMessage(err.response);
      this.setState({
        loading: false
      })
      hideVisible && hideVisible()
    })
  }

  handleChangePage = (value, index, checkResult, page, pageSize) => {

    const {readonly, user, hrInfo, showVisible, hideVisible} = this.props
    hideVisible && hideVisible()
    this.setState({
      loading: true
    })
    GreenCodeService.checkOne(value.type.substring("CHECK_OPTION_".length, value.type.length), this.state.userOID, page - 1, pageSize).then(res => {
      const list = checkResult.list;
      list[index] = res.data

      this.setState({
        checkResult: checkResult,
        loading: false,
        checkDate: new Date().getTime(),
        // timeoutTask: setTimeout(() => this.setState({timeoutVisible: true}), 60 * 1000)
      })
      this.setState({timeoutVisible: false})
      if (res.data.success) {
        showVisible && showVisible()
      } else {
        hideVisible && hideVisible()
      }
    }).catch((err) => {
      errorMessage(err.response);
      this.setState({
        loading: false
      })
      hideVisible && hideVisible()
    })

  }

  getColumns = (type, page = 0, size = 10) => {
    const checkOptionColumnArr = CheckOptionsColumnMap[type] || []

    return [
      {
        title: '序号',
        dataIndex: 'id',
        key: 'id',
        width: 60,
        render: (text, record, index) => `${page * size + index + 1}`
      }
    ].concat(checkOptionColumnArr.map(field => {
      return {
        title: ColumnMap[field] || field.name,
        dataIndex: field,
        key: field,
        width: columnsWidthMap[field] || 240,
        // render: ColumnMap[field] ? null : (text, record) => field.value,
        render: (value, record) => {
          let v = ColumnMap[field] ? value : field.value

          if(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(v)){
            v = v.replace(/[TZ]/g, ' ')
          }

          try{
            if(/^-?\d+(\.\d)*$/.test(v) && ColumnMap[field] && ColumnMap[field].indexOf("金额") > -1){
              v = v.toFixed(2)
            }
          }catch (e) {
          }

          return (
            // 当不在Map中，则为固定值
            <Popover placement="topLeft" content={v}>{v}</Popover>
          );
        }
      }
    }))
  }

  componentWillUnmount() {
    clearTimeout(this.state.timeoutTask)
  }

  componentDidMount() {
    const {readonly, user, hrInfo, showVisible, hideVisible} = this.props
    if (!readonly) {
      this.checkAll()
    }

    GreenCodeService.getCheckOptions().then(res => {
      if (readonly) {
        const list = res.data.map((value) => {
          return {type: value, success: true, pageList: {size: 10, totalElements: 0}}
        })
        this.setState({
          checkResult: {
            success: true, list: list
          }
        })
      }

      this.setState({
        optionList: res.data
      })
    }).catch((err) => {
      errorMessage(err.response);
    })
  }

  render() {
    const {readonly, user, hrInfo, showVisible, hideVisible} = this.props
    const {checkResult, loading} = this.state
    const defaultActiveKey = (checkResult.list || []).filter((value) => !value.success).map((value, index) => value.type)
    return (<div className="green-code">
      <Modal
        title="超时错误"
        visible={this.state.timeoutVisible}
        onOk={this.checkAll}
        okText="确认"
        footer={
          <Button key="submit" type="primary" loading={loading} onClick={this.checkAll}>
            确认
          </Button>
        }
      >
        <Alert
          message="超时错误"
          description="由于太长时间没有操作，请点击确认并重新检查。"
          type="error"
          showIcon
        />
      </Modal>
      <Spin tip="Loading..." spinning={loading}>
        <div className="request-info">
          <ReactIF rif={readonly}>
            <h3 className="sub-header-title">{messages("green-code.key36")/*绿码检查结果*/}</h3>
            <GiftDeclareTitle relse>{messages("green-code.key36")/*绿码检查结果*/}</GiftDeclareTitle>
          </ReactIF>

          <ReactIF rif={checkResult.success || readonly}>
            <Alert
              message={messages("green-code.key32")/*健康码检查通过*/}
              description={messages("green-code.key33")/*您的健康码已通过检查，可以点击发起申请，继续操作。*/}
              type="success"
              showIcon
              style={{marginBottom: '20px'}}
            />
            <Alert relse
                   message={messages("green-code.key34")/*健康码检查未通过*/}
                   description={messages("green-code.key35")/*您的健康码未通过检查，可以点击未通过项，查看详情。*/}
                   type="error"
                   showIcon
                   style={{marginBottom: '20px'}}
            />
          </ReactIF>
        </div>
        <div className="request-info">
          <ReactIF rif={readonly}>
            <h3 className="sub-header-title">{messages("green-code.key37")/*绿码申请检查项*/}</h3>
            <GiftDeclareTitle relse>{messages("green-code.key37")/*绿码申请检查项*/}</GiftDeclareTitle>
          </ReactIF>
          <ReactIF rif={checkResult.list && checkResult.list.length > 0}>
            <Collapse expandIconPosition={'right'}
                      defaultActiveKey={defaultActiveKey}
                      onChange={callback}>
              {checkResult.list.map((value, key) => {
                return <Panel disabled={value.success}
                              header={<div>
                                {CheckOptionsMap[value.type] || value.type}
                                <ReactIF rif={value.success}>
                                  <Tag className="head-tag" color="#00a650">
                                    <Icon type="check"/> 通过
                                  </Tag>
                                  <Tag relse className="head-tag" color="#DF0000">
                                    <Icon type="close"/> 未通过
                                  </Tag>
                                </ReactIF>
                              </div>}
                              key={value.type}>
                  <Table scroll={{x: 'max-content'}}
                         dataSource={value.list}
                         columns={this.getColumns(value.type, value.pageList.number, value.pageList.size)}
                         pagination={{
                           pageSize: value.pageList.size,
                           total: value.pageList.totalElements,
                           onChange: (page, pageSize) => this.handleChangePage(value, key, checkResult, page, pageSize)
                         }} bordered/>
                </Panel>
              })}
            </Collapse>
          </ReactIF>
        </div>
      </Spin>
    </div>);
  }
}

GreenCodeStateCollapse
  .propTypes = {
  readonly: React.PropTypes.bool,
  form: React.PropTypes.any,
  user: React.PropTypes.any,
  hrInfo: React.PropTypes.any,
  showVisible: React.PropTypes.func,
  hideVisible: React.PropTypes.func,
};
export default GreenCodeStateCollapse;
